<script setup lang="tsx">
import { Button, Popconfirm, Tag } from 'ant-design-vue';
import { deleteBatchUser, deleteUser, fetchGetUserList } from '@/service/api';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import { enableStatusRecord, userGenderRecord } from '@/constants/business';
import UserOperateDrawer from './modules/user-operate-drawer.vue';
import UserSearch from './modules/user-search.vue';

const { tableWrapperRef, scrollConfig } = useTableScroll();

enum Roles {
  SUPER = '超级管理员',
  ADMIN = '老师',
  USER = '学生'
}

const rolesMap = {
  R_SUPER: Roles.SUPER,
  R_ADMIN: Roles.ADMIN,
  R_USER: Roles.USER
};

const {
  columns,
  columnChecks,
  data,
  getData,
  getDataByPage,
  loading,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetUserList,
  apiParams: {
    current: 1,
    size: 10
    // if you want to use the searchParams in Form, you need to define the following properties, and the value is null
    // the value can not be undefined, otherwise the property in Form will not be reactive
    // state: undefined,
    // userName: undefined,
    // gender: undefined,
    // phone: undefined,
    // email: undefined
  },
  columns: () => [
    {
      key: 'userId',
      title: '学号',
      dataIndex: 'userId',
      align: 'center',
      width: 100
    },
    {
      key: 'userName',
      dataIndex: 'userName',
      title: $t('page.manage.user.userName'),
      align: 'center',
      minWidth: 64
    },
    {
      key: 'gender',
      title: $t('page.manage.user.userGender'),
      align: 'center',
      dataIndex: 'gender',
      width: 60,
      customRender: ({ record }) => {
        if (record.gender === null) {
          return null;
        }

        const tagMap: Record<Api.SystemManage.UserGender, string> = {
          1: 'processing',
          2: 'error'
        };

        const label = $t(userGenderRecord[record.gender]);

        return <Tag color={tagMap[record.gender]}>{label}</Tag>;
      }
    },
    {
      key: 'age',
      dataIndex: 'age',
      title: '年龄',
      align: 'center',
      width: 60
    },
    {
      key: 'phone',
      dataIndex: 'phone',
      title: $t('page.manage.user.userPhone'),
      align: 'center',
      minWidth: 120
    },
    {
      key: 'email',
      dataIndex: 'email',
      title: $t('page.manage.user.userEmail'),
      align: 'center',
      minWidth: 200
    },
    {
      key: 'department',
      dataIndex: 'department',
      title: '学院',
      align: 'center',
      minWidth: 200
    },
    {
      key: 'className',
      dataIndex: 'className',
      title: '班级',
      align: 'center',
      minWidth: 200
    },
    {
      key: 'faceInfo',
      dataIndex: 'faceInfo',
      title: '人脸信息',
      align: 'center',
      width: 80
    },
    {
      key: 'roles',
      dataIndex: 'roles',
      title: '角色',
      align: 'center',
      width: 80,
      customRender: ({ record }) => {
        const roles = Array.isArray(record.roles) ? record.roles : [record.roles];
        return roles.map(role => rolesMap[role as keyof typeof rolesMap] || '未知角色').join(', ');
      }
    },
    {
      key: 'state',
      dataIndex: 'state',
      title: $t('page.manage.user.userStatus'),
      align: 'center',
      width: 100,
      customRender: ({ record }) => {
        if (record.state === null) {
          return null;
        }

        const tagMap: Record<Api.Common.EnableStatus, string> = {
          1: 'success',
          2: 'warning'
        };

        const label = $t(enableStatusRecord[record.state]);

        return <Tag color={tagMap[record.state]}>{label}</Tag>;
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      customRender: ({ record }) => (
        <div class="flex-center gap-8px">
          <Button type="primary" ghost size="small" onClick={() => edit(record.userId)}>
            {$t('common.edit')}
          </Button>
          <Popconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(record.userId)}>
            <Button danger size="small">
              {$t('common.delete')}
            </Button>
          </Popconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  rowSelection,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

async function handleBatchDelete() {
  // request
  await deleteBatchUser(checkedRowKeys.value);

  onBatchDeleted();
}

async function handleDelete(userId: number) {
  // request
  await deleteUser(userId);

  onDeleted();
}

function edit(id: number) {
  handleEdit(id);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <UserSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <ACard
      :title="$t('page.manage.user.title')"
      :bordered="false"
      :body-style="{ flex: 1, overflow: 'hidden' }"
      class="flex-col-stretch sm:flex-1-hidden card-wrapper"
    >
      <template #extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        />
      </template>
      <ATable
        ref="tableWrapperRef"
        :columns="columns"
        :data-source="data"
        size="small"
        :row-selection="rowSelection"
        :scroll="scrollConfig"
        :loading="loading"
        row-key="userId"
        :pagination="mobilePagination"
        class="h-full"
      />

      <UserOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
    </ACard>
  </div>
</template>

<style scoped></style>
